﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Aliyun.MNS;
using Aliyun.MNS.Model;

namespace Framework.MQS
{
    public class AliyunMessageQueue : MessageQueue
    {
        private const string _accessKeyId = "c0j2z6IGYrDP7jVe";
        private const string _secretAccessKey = "K6QRsaqEOq7dTQup5nmugI4QJRWqwO";
        private const string _endpoint = "http://1307221029824444.mns.cn-qingdao.aliyuncs.com";
        private readonly IMNS _client;
        private const string _queueName = "logQueue";
        private static readonly AutoResetEvent _autoSetEvent = new AutoResetEvent(false);
        public AliyunMessageQueue()
        {
            _client = new MNSClient(_accessKeyId, _secretAccessKey, _endpoint);
        }

        internal override void SendMessage(string messageBody)
        {
            var nativeQueue = _client.GetNativeQueue(_queueName);
            //var sendMessageResponse = nativeQueue.SendMessage("Hello world!", 10, 4);
            var sendMessageRequest = new SendMessageRequest(messageBody);
            var sendMessageResponse = nativeQueue.SendMessage(sendMessageRequest);
            //nativeQueue.BeginSendMessage(sendMessageRequest, SendMessageCallback, nativeQueue);
            //_autoSetEvent.WaitOne();
        }
        private void SendMessageCallback(IAsyncResult ar)
        {
            try
            {
                var nativeQueue = (Queue)ar.AsyncState;
                var response = nativeQueue.EndSendMessage(ar);
                //_autoSetEvent.Set();
            }
            catch (Exception ex)
            {
            }
        }
        internal override void BatchSendMessage()
        {

        }

        internal override void ReceiveMessage()
        {
            var nativeQueue = _client.GetNativeQueue(_queueName);
            var receiveMessageResponse = nativeQueue.ReceiveMessage();
            var mes = receiveMessageResponse.Message;
            nativeQueue.DeleteMessage(mes.ReceiptHandle);
        }

        internal override void BatchReceiveMessage()
        {
            throw new NotImplementedException();
        }

        internal override void DeleteMessage()
        {
            throw new NotImplementedException();
        }

        internal override void BatchDeleteMessage()
        {
            throw new NotImplementedException();
        }

        internal override void PeekMessage()
        {
            throw new NotImplementedException();
        }

        internal override void BatchPeekMessage()
        {
            throw new NotImplementedException();
        }
    }
}
